package win.larryzeal.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class URLConnectionUtil {
	/**
	 * 创建一个HttpURLConnection对象，注意，需要手动调用其connect() 方法才会建立连接。可能返回null。
	 * 
	 * @param urlString
	 *            建立连接的目标地址。
	 * @param method
	 *            GET(default),POST,...
	 * @param connectionTimeout
	 *            0 for no timeout.
	 * @param readTimeout
	 *            0 for no timeout.
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection create(String urlString, String method, int connectionTimeout, int readTimeout) throws IOException {
		HttpURLConnection conn = null;
		URL url = new URL(urlString);
		conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(connectionTimeout);
		conn.setReadTimeout(readTimeout);

		conn.setRequestMethod(method);
		// conn.connect();

		return conn;

	}

	/**
	 * 无超时。
	 * 
	 * @param urlString
	 * @param method
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection create(String urlString, String method) throws IOException {
		return create(urlString, method, 0, 0);
	}

	/**
	 * 无超时，默认GET请求。
	 * 
	 * @param urlString
	 * @return
	 * @throws IOException
	 */
	public static HttpURLConnection create(String urlString) throws IOException {
		return create(urlString, "GET", 0, 0);
	}

	/**
	 * 只能用于java URL打开的连接。
	 * 
	 * @param conn
	 * @return
	 * @throws IOException
	 */
	public static String getResponseBody(HttpURLConnection conn, String charsetName) throws IOException {
		// 输出内容，响应体。
		InputStream inputStream = conn.getInputStream();
		if (inputStream == null) {
			return null;
		}
		int len = 1024;
		byte[] bs = new byte[len];
		int off = 0;

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		while (off != -1) {
			off = inputStream.read(bs, 0, len);
			if (off != -1)
				baos.write(bs, 0, off);
			else
				baos.flush();
		}
		baos.close();
		inputStream.close();
		if (charsetName == null) {
			return baos.toString();
		}
		return baos.toString(charsetName);
	}

	public static String getResponseBody(HttpURLConnection conn) throws IOException {
		return getResponseBody(conn, null);
	}


}
